/**
 * myNetwork block provides interface for basic network operations,
 * --> NetConnect provides interface to establish a socket connect to a server
 * --> ClientListen establish a watcher to listen to this socket
 * --> one thing to notice, only one socket is established to our server
 * <p>
 * InetAddress inetAddress=InetAddress.getByName("javalobby.org");
 * InetSocketAddress inetSocketAddress=new InetSocketAddress(HostIp,HostPort);
 * just an example to tell you how to use domain name
 */

package com.tjian.fafa.user.base.myNetwork;

import com.tjian.fafa.user.base.ConnectedApp;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.config.ConfigOfFafa;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public class NetConnect extends Thread
{

    private String hostIp = ConfigOfFafa.serverIp;

    private int hostPort = ConfigOfFafa.imPort;

    /*  socket  */
    private Socket socket = null;

    private boolean connectedAlready = false;

    public NetConnect()
    {

    }

    public void run()
    {
        try
        {
            sleep(100); // to wait for the connection to be stable
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        try
        {
            InetAddress inetAddress = InetAddress.getByName(hostIp);// initialization and establish connection
            InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, hostPort);
            socket = new Socket();
            socket.connect(inetSocketAddress, 2000);
            if (socket.isConnected())
            {
                connectedAlready = true;
            }
            else
            {
                connectedAlready = false;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public Socket getSocket()
    {
        return socket;
    }

    public boolean connectedOrNot()
    {
        return connectedAlready;
    }

}